<template>
  <div class="table-box card">
    <div class="ed-head">
      <span class="title">{{ documentStatus === "edit" ? "修改" : documentStatus === "add" ? "新增" : "" }}入库订单</span>
      <el-icon class="pointer" @click="router.go(-1)"><CloseBold /></el-icon>
    </div>
    <el-form :model="purchaseForm" label-width="120px" :rules="couponRules" ref="ruleFormRef" :inline="true">
      <el-form-item label="单据编号" prop="orderNo">
        <el-input class="width240" v-model="purchaseForm.orderNo" disabled placeholder="系统自动生成" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-input class="width240" v-model="purchaseForm.supplierName" disabled>
          <template #append>
            <el-button type="primary" :icon="MoreFilled" @click="openRadioTreeTable('选择供应商', 0)" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="入库日期" prop="date">
        <el-date-picker class="width240" v-model="purchaseForm.date" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input class="width240" v-model="purchaseForm.remark" placeholder="请填写" :rows="1" type="textarea" />
      </el-form-item>
    </el-form>
    <ProTable
      ref="proTable"
      row-key="id"
      :columns="columns"
      :data="purchaseForm.stockindetailList"
      :pagination="false"
      :is-card="false"
      show-summary
      :summary-method="getSummaries"
      :tool-button="documentStatus !== 'audited'"
    >
      <template #tableHeader>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择原料')">
          添加原料
        </el-button>
      </template>
      <template #toolButton>
        <!-- 待审核才能确认收货 -->
        <el-button v-if="purchaseForm.status === 1 || documentStatus === 'add'" type="primary" @click="onSubmitGoods">
          保存并审核
        </el-button>
        <el-button v-if="documentStatus !== 'audited'" @click="onSubmit" type="primary"> 保存 </el-button>
        <el-button v-if="documentStatus !== 'audited'" @click="router.go(-1)"> 返回 </el-button>
      </template>
      <template #operate="scope">
        <!-- <el-button type="danger" size="small" @click="delSpecRow(scope.$index)" v-if="documentStatus !== 'audited'">
          删除
        </el-button> -->
        <div class="flx-justify-between">
          <el-icon size="18" color="#169D82" @click="openSelectTreeTable('选择原料')"><Plus /></el-icon>
          <el-icon @click="delSpecRow(scope.$index)" size="18" color="#f00"><Minus /></el-icon>
        </div>
      </template>
      <!-- 😊😊编码区域 start-->
      <!-- <template #barcode="scope">
        <el-input
          class="w100"
          v-model="scope.row.barCode"
          @change="onSearchCode"
          :disabled="documentStatus === 'audited'"
          @keyup.enter="handleKeyup($event, scope.$index, 1, scope.row.isGift)"
          :ref="'input' + String(scope.$index) + String(1)"
          @input="onGoodsSearch(scope, $event)"
        >

          <template #append>
            <el-button
              type="primary"
              :icon="MoreFilled"
              :disabled="documentStatus === 'audited'"
              @click="openSelectTreeTable('选择原料')"
            />
          </template>
        </el-input>
         @keyup.enter="handleKeyup($event, scope.$index, 1, scope.row.isGift)" 回车事件
      </template> -->
      <!-- v-model="scope.row.barCode" -->
      <template #barcode="scope">
        <el-input
          class="w100"
          v-model="purchaseForm.stockindetailList[scope.$index].barcode"
          @change="onSearchCode"
          :disabled="documentStatus === 'audited'"
          :ref="'input' + String(scope.$index) + String(1)"
          @input="onGoodsSearch(scope, $event)"
        >
          <template #append>
            <el-button
              type="primary"
              :icon="MoreFilled"
              :disabled="documentStatus === 'audited'"
              @click="openSelectTreeTable('选择原料')"
            />
          </template>
        </el-input>
      </template>
      <!--编码区域 end -->

      <!-- 1😊：仓库start -->
      <template #warehouse="{ $index }">
        <el-select :disabled="documentStatus === 'audited'" v-model="purchaseForm.stockindetailList[$index].houseId" size="large">
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </template>
      <!--仓库end -->

      <template #quantity="scope">
        <el-input-number
          class="w100"
          v-model="scope.row.quantity"
          :controls="false"
          :precision="2"
          :min="0"
          :disabled="documentStatus === 'audited' || scope.row.isGift"
          @change="onChangeAmo(scope.$index)"
          :ref="'input' + String(scope.$index) + String(2)"
          @keyup.enter="handleKeyup($event, scope.$index, 2, scope.row.isGift)"
          @focus="event => event.target.select()"
        />
      </template>
      <template #price="scope">
        <el-input-number
          class="w100"
          :controls="false"
          :precision="2"
          v-model="scope.row.price"
          :disabled="documentStatus === 'audited' || scope.row.isGift"
          @change="onChangeAmo(scope.$index)"
          :ref="'input' + String(scope.$index) + String(3)"
          @keyup.enter="handleKeyup($event, scope.$index, 3, scope.row.isGift)"
          @focus="event => event.target.select()"
        />
      </template>
      <template #taxRate="scope">
        <el-input-number
          class="w100"
          :precision="2"
          :controls="false"
          v-model="scope.row.taxRate"
          :disabled="documentStatus === 'audited'"
          :ref="'input' + String(scope.$index) + String(4)"
          @keyup.enter="handleKeyup($event, scope.$index, 4, scope.row.isGift)"
          @focus="event => event.target.select()"
        />
      </template>
      <!--赠品先不做 <template #isGift="scope">
        <el-switch v-model="scope.row.isGift" :disabled="documentStatus === 'audited'" />
      </template> -->
      <!--赠送数量也先不做 <template #giftQuantity="scope">
        <el-input-number
          :precision="2"
          class="w100"
          :controls="false"
          v-model="scope.row.giftQuantity"
          :disabled="documentStatus === 'audited' || !scope.row.isGift"
          :ref="'input' + String(scope.$index) + String(5)"
          @keyup.enter="handleKeyup($event, scope.$index, 5, scope.row.isGift)"
          @focus="event => event.target.select()"
        />
      </template> -->
    </ProTable>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
    <SelectTreeTable @radio="onRadio" ref="radioTreeTableRef" />
  </div>
</template>
<script setup lang="ts" name="waresEdit">
import { ref, reactive, onMounted, getCurrentInstance, nextTick, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
// confirmStockin 确认收货
import {
  createStockin,
  editStockin,
  getStockin,
  getSupplierList,
  getWaresCategoryList,
  getWaresList,
  getSupplierRegionList,
  confirmStockin,
  getStorehouseList,
  getIndistinctWaresList
} from "@/api/modules/inventory";
// getStorehouseList:获取仓库表
import ProTable from "@/components/ProTable/index.vue";
import { MoreFilled } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
// import { replaceArrayItems } from "@/utils";
import { ElMessage } from "element-plus";
import { useDebounceFn } from "@vueuse/core";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const documentStatus = ref("add");
// 发请求使用的数据
const purchaseForm = reactive({
  id: 0,
  orderType: 1,
  orderNo: "",
  supplierName: "",
  supplierId: "",
  date: "",
  status: 2,
  checkFlag: 1,
  remark: "",
  sourceId: "",
  printStatus: 0,
  // 表格渲染的数据
  stockindetailList: []
});

watch(
  () => purchaseForm.supplierId,
  newV => {
    console.log(newV);
  },
  { immediate: true }
);

// 规则
const couponRules = reactive({
  // orderNo: [{ required: true, message: "请填写订单编号" }],
  supplierId: [{ required: true, message: "请选择供应商" }],
  date: [{ required: true, message: "请选择入库日期" }],
  stockindetailList: [{ required: true, message: "请添加原料" }]
});

// 原料区域的减
const delSpecRow = (index: number) => {
  if (purchaseForm.stockindetailList.length <= 1) return ElMessage.error("至少要保留一条记录");
  purchaseForm.stockindetailList.splice(index, 1);
};
// 原料区域的加
const onRadio = (row: any) => {
  purchaseForm.supplierId = row.data.id;
  purchaseForm.supplierName = row.data.name;
};

// 外层表格的列的每一项
const columns: ColumnProps<Inventory.ResPurchaseList>[] = [
  { type: "index", label: "序号", width: 60 },
  { prop: "operate", label: "操作", width: 80 },
  { prop: "barcode", label: "编码" },
  { prop: "warehouse", label: "仓库", width: 170 },
  { prop: "goodsName", label: "名称" },
  { prop: "productName", label: "规格", width: 130 },
  { prop: "quantity", label: "数量", width: 130 },
  {
    prop: "unitName",
    label: "单位",
    width: 120
  },
  // {
  //   prop: "convert",
  //   label: "",
  //   width: 130
  // },
  {
    prop: "unitBasis",
    label: "基准单位数量",
    width: 130
  },
  { prop: "price", label: "采购价", width: 130 },
  { prop: "amount", label: "金额", width: 100 }
  // { prop: "taxRate", label: "税率", minWidth: 120 }
  // { prop: "isGift", label: "是否赠品", minWidth: 120 },
  // { prop: "giftQuantity", label: "赠送数量", minWidth: 120 }
];

const radioTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openRadioTreeTable = (title: string, ix: number) => {
  const params = {
    title,
    isView: false,
    index: ix,
    selType: "radio",
    columns: [
      { type: "radio", label: "#", width: 60 },
      { prop: "name", label: "供应商名称", align: "left" }
    ],
    idName: "supplierCode",
    treeApi: getSupplierRegionList,
    api: getSupplierList
  };
  radioTreeTableRef.value?.acceptParams(params);
};

// 输入数据时并修改数据打开弹窗
// const onSearchCode = (value: string | number) => {
//   if (Object.entries(value).length !== 0) {
//     openSelectTreeTable("选择原料", value);
//   }
// };

// 勾选中仓库触发
const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map(im => {
      return {
        goodsName: im.name,
        goodsId: im.id,
        products: im.productName,
        productsId: im.prodcutId,
        productName: im.productName,
        quantity: 1,
        barcode: im.barcode,
        price: im.purPrice,
        amount: im.purPrice,
        taxRate: 0,
        isGift: false,
        giftQuantity: 0,
        unitName: im.unitName,
        convert: im.convert,
        houseId: defaultHouserId.value,
        unitBasis: im.convert
      };
    });

    list.forEach(v => {
      if (!purchaseForm.stockindetailList.some(i => i.productsId === v.productsId)) {
        purchaseForm.stockindetailList.push(v);
      }
    });
    // 数组去重避免有重复的数据
    // purchaseForm.stockindetailList = replaceArrayItems(list, purchaseForm.stockindetailList, "goodsId");
    // purchaseForm.stockindetailList = list;
  }
};

interface SummaryMethodProps<T = Inventory.ResPurchaseList> {
  columns: TableColumnCtx<T>[];
  data: T[];
}

// const add = () => {
//   purchaseForm.stockindetailList.push({
//     goodsName: "",
//     goodsId: 0,
//     products: "",
//     productsId: 0,
//     productName: 0,
//     quantity: 0,
//     price: 0,
//     amount: 0,
//     taxRate: 0,
//     isGift: false,
//     giftQuantity: 0,
//     houseId: defaultHouserId.value
//   });
// };

// 计算合计数据 param就是$event
const getSummaries = (param: SummaryMethodProps) => {
  console.log(param);

  const { columns, data } = param;
  const props: string[] = ["quantity", "amount", "giftQuantity"];
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (!props.includes(column.property)) {
      sums[index] = "";
      return;
    }

    let valuesToSum: number[] = [];
    data.forEach(item => {
      if (column.property === "quantity" && item.isGift) {
        return; // 如果isGift为true，则不统计quantity
      }
      if (column.property === "amount" && item.isGift) {
        return; // 如果isGift为true，则不统计amount
      }
      if (column.property === "giftQuantity" && !item.isGift) {
        return; // 如果isGift为false，则不统计giftQuantity
      }
      const value = Number(item[column.property]);
      if (!Number.isNaN(value)) {
        valuesToSum.push(value);
      }
    });

    if (valuesToSum.length > 0) {
      sums[index] = `${valuesToSum.reduce((prev, curr) => prev + curr, 0)}`;
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// 保存添加的原料
const onSubmit = () => {
  if (purchaseForm.supplierId === "") return ElMessage.error("请选择供应商");
  if (purchaseForm.date === "") return ElMessage.error("请选择日期");
  if (purchaseForm.stockindetailList.length < 1) return ElMessage.error("请添加原料");
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    purchaseForm.status = 1;
    try {
      if (documentStatus.value === "edit") {
        await editStockin(purchaseForm).then(() => {
          router.push({
            path: "/procure/warehousing",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createStockin(purchaseForm).then(() => {
          router.push({
            path: "/procure/warehousing",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};
const onChangeAmo = (index: number) => {
  purchaseForm.stockindetailList[index].amount = (
    purchaseForm.stockindetailList[index].price * purchaseForm.stockindetailList[index].quantity
  ).toFixed(2);
  // 计算基准单位
  purchaseForm.stockindetailList[index].unitBasis =
    purchaseForm.stockindetailList[index].convert * purchaseForm.stockindetailList[index].quantity;
};
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);

// 里层表格数据
const openSelectTreeTable = (title: string, searchVal: string | number) => {
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: "prodcutId",
    selTags: purchaseForm.stockindetailList
      .filter(age => age.goodsId !== 0)
      .map(i => {
        i.name = i.goodsName;
        i.id = i.productsId;
        return i;
      }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "barcode", label: "编码", align: "left", width: 200 },
      { prop: "name", label: "原料名称", align: "left", minWidth: 220 },
      { prop: "productName", label: "规格", align: "left", minWidth: 100 },
      { prop: "unitName", label: "单位", align: "left", minWidth: 160 },
      // { prop: "posPrice", label: "原料价格", minWidth: 120 }
      { prop: "purPrice", label: "采购价格", minWidth: 120 }
    ],
    idName: "goodsCategoryId",
    // 发请求
    treeApi: getWaresCategoryList,
    api: getWaresList
  };
  selectTreeTableRef.value?.acceptParams(params);
};
const supplierList = ref([]);
// const storeList = ref([]);
const { proxy } = getCurrentInstance();
const refsInputName = ref("");

// 输入数据自动计算数据得输入框谁有焦点
const handleKeyup = (event: any, index: number, cellIndex: number, isGift: boolean) => {
  if (cellIndex < 4 && !isGift) {
    refsInputName.value = "input" + String(index) + String(cellIndex + 1);
  } else if (cellIndex === 1 && isGift) {
    refsInputName.value = "input" + String(index) + "4";
  } else if (cellIndex === 4 && isGift) {
    refsInputName.value = "input" + String(index) + "5";
  } else {
    refsInputName.value = "input" + String(index + 1) + "1";
  }
  if (proxy.$refs[refsInputName.value]) {
    nextTick(() => {
      event.target.blur();
      proxy.$refs[refsInputName.value].focus();
    });
  }
};

onMounted(async () => {
  try {
    const [supplier] = await Promise.all([
      getSupplierList()
      // getStoreList()
      // useSelectStore().getDic("DiscountType")
    ]);
    supplierList.value = supplier.data.list;
    // storeList.value = store.data.list;
    if (route.query.id) {
      // 获取入库单信息
      getStockin({ id: route.query.id }).then(res => {
        // console.log(res);··········

        // 判断是否能使用
        if (res.data.checkFlag) {
          documentStatus.value = "audited";
          columns[1].isShow = false;
        } else {
          documentStatus.value = "edit";
        }
        Object.keys(purchaseForm).forEach(key => {
          if (res.data.hasOwnProperty(key)) {
            purchaseForm[key] = res.data[key];
          }
        });
      });
    } else {
      // purchaseForm.storeId = store.data.list[0].id;
      purchaseForm.supplierId = supplier.data.list[0].id;
      purchaseForm.supplierName = supplier.data.list[0].name;
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
  onShowStore();
});

// 原料编码输入框事件+防抖
const onGoodsSearch = useDebounceFn(async (scope, $event) => {
  if ($event === "") return;
  // console.log(scope, $event);
  // getIndistinctWaresList  模糊查询原料
  const res = await getIndistinctWaresList({ content: $event });
  console.log(res);
  if (res.data?.length > 1) {
    openSelectTreeTable("选择原料", $event);
  } else {
    if (res.data?.length > 0) {
      let list = res.data.map(im => {
        return {
          goodsName: im.name,
          goodsId: im.id,
          products: im.productName,
          productsId: im.prodcutId,
          productName: im.productName,
          quantity: 1,
          barcode: im.barcode,
          price: im.purPrice,
          amount: im.purPrice,
          taxRate: 0,
          isGift: false,
          giftQuantity: 0,
          convert: im.convert,
          houseId: defaultHouserId.value
        };
      });

      if (!purchaseForm.stockindetailList.some(e => list[0].productsId === e.productsId)) {
        purchaseForm.stockindetailList = [...purchaseForm.stockindetailList, ...list];
      }
    }
  }
}, 500);

/* 仓库start */
const storeList = ref<any[]>([]);
const defaultHouserId = ref("");
const onShowStore = async () => {
  const res = await getStorehouseList();
  storeList.value = res.data.list;
  storeList.value.forEach(v => {
    if (v.isDefault) {
      defaultHouserId.value = v.id;
    }
  });
};

/* 仓库end */

// 确认收货并审核
const onSubmitGoods = async () => {
  if (purchaseForm.supplierId === "") return ElMessage.error("请选择供应商");
  if (purchaseForm.date === "") return ElMessage.error("请选择日期");
  if (purchaseForm.stockindetailList.length < 1) return ElMessage.error("请添加原料");
  await ruleFormRef.value.validate();
  await confirmStockin(purchaseForm);
  // console.log(res);
  ElMessage.success("审核成功");
  router.push({
    path: "/procure/warehousing",
    query: {
      upList: true
    }
  });
};
</script>

<style lang="scss" scoped></style>
